#include<process.h>
#include<BuildTable.h>
#include<math.h>
void showbits(int);
void binary_2_number(int,int);

FILE *fp1;
int ans;
main()
{
 FILE *fp;
 char fname[30],fname1[30];
 int ch,ch1;
 int pos=1;
 struct node *head=NULL;
 BuildTable BT;
 clrscr();
 printf("Enter File name 2 decompress:");
 scanf("%s",fname);
 fp=fopen(fname,"rb");
 if(fp==NULL)
 {
  printf("%s Not Found \nLine 1",fname);
  getch();
  exit(0);
 }
 printf("Enter destination File Path:");
 scanf("%s",fname1);
 fp1=fopen("c:/temp.neo","wb");
 if(fp1==NULL)
 {
   printf("%s Not Found\n Error during decompression\nLine 2",fname);
  getch();
  exit(0);
 }
  while((ch=fgetc(fp))!='`')
   {
	  BT.create(&head,ch);
   }
   BT.display(head);

  int totalChar=BT.getTotalChar(head);
  while((ch=fgetc(fp))!=EOF)
	showbits(ch);
//   fputc(EOF,fp1);
  fcloseall();
 fp=fopen(fname1,"wb");

 if(fp==NULL)
 {
  printf("%s Not Found\nLine 3",fname1);
  getch();
  exit(0);
 }

  fp1=fopen("c:/temp.neo","rb");
  if(fp1==NULL)
  {
	printf("%s Not Found\n Error during decompression\nLine 4",fname);
	getch();
	exit(0);
  }
 ch=0;
 pos=0;
 int size=getSizeOfBits(totalChar);
  while(ch!=EOF)
  {
	   while((ch=fgetc(fp1)))
	   {
		  binary_2_number(ch,pos);
		 pos++;
		 if(ch==EOF||pos==size)
		  break;
		}
	 ch1=(char)BT.getCharacter(&head,ans);
  //	  printf("ch1=%c  pos=%d\n",ch,pos);
	 ans=0;
	 pos=0;
	  if(ch==EOF)
	   break;
	   if(ch1==NULL)
	   {
		printf("Character Not Found \nError During Decompression5");
		getch();
		exit(0);
	   }
	 fputc(ch1,fp);
  }
 fcloseall();
 return 0;
}

void showbits(int ch)
  {
   int i,k,mask;
 // printf("%c  %d\n",ch,ch);
 for(i=7;i>=0;i--)
   {
	 mask=1<<i;
	 k=ch&mask;
	 if(k==0)
	 {
	// printf("0");
	 fputc('0',fp1);
	// cnt++;
	 }
	 else
	  {
	 // printf("1");
	  fputc('1',fp1);
	 // cnt1++;
	 }
   }
 }



 void  binary_2_number(int ch,int i)
{
   int temp;
   if(ch=='1')
   {
	 temp=pow(2,i);
	// printf("  temp=%d",temp);
	 ans=ans+temp;
   }
   else
	 ans=ans+0;
}



